//
//  ContextModel.m
//  Depressed.domo
//
//  Created by rimi on 16/6/1.
//  Copyright © 2016年 薛涛. All rights reserved.
//

#import "ContextModel.h"
#import "Person.h"
@implementation ContextModel

static ContextModel *contextModel = nil;
+ (ContextModel *)shareContextModel {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        contextModel = [[ContextModel alloc]init];
        
    });
    return contextModel;
}

//初始化上下文
- (void)initWithContext {
    /*  初始化工作  */
    //沙盒文档文件夹地址
    NSString *home = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //硬盘中数据库具体位置
    NSString *path = [home stringByAppendingPathComponent:@"fenzu.db"];
    NSLog(@"%@",path);
    
    //路径转化为URL地址
    NSURL *url = [NSURL fileURLWithPath:path];
    
    //在内存中开辟一个上下文空间
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    
    //创建一个model用于调度器确定存取结构
    NSManagedObjectModel  *model = [NSManagedObjectModel mergedModelFromBundles:nil];
    //为上下文创建一个调度器用于硬盘存取
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:model];
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:nil];
    context.persistentStoreCoordinator = coordinator;
    
    self.context = context;
}

#pragma mark ** 得到SQL数据源 **
- (void)getWithDataSourceArrM {
    
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:self.context];
    [request setEntity:entity];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
    NSArray *sortArray = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
    //设置排序方式
    [request setSortDescriptors:sortArray];
    
    //数据返回到可变数组
    _fetchArrM = [[self.context executeFetchRequest:request error:nil]mutableCopy];
    
    self.dataSourceArrM = [[NSMutableArray alloc]init];
    for (Person *obj in _fetchArrM) {
        NSDictionary *dic = @{@"name":obj.name,@"age":obj.age,};
        [self.dataSourceArrM addObject:dic];
    }
    NSLog(@"%@",self.dataSourceArrM);
}

/*  增  */
- (void)insertContextObject:(NSString *)nameField ageField:(NSString *)ageField {
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    person.name = nameField;
    person.age = ageField;
    
    NSError *error = nil;
    //将上下文中的数据保存到本地数据库中
    [self.context save:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    else {
        NSLog(@"插入成功");
    }
    [self getWithDataSourceArrM];
}

/*  删  */
- (void)deleteContextObject:(NSManagedObject *)object {
    //通过上下文删除这条模型
    [_context deleteObject:object];
    [_context save:nil];
    [self getWithDataSourceArrM];
    
}
@end
